#!/bin/bash

# 隧道映射 API 测试脚本
# 测试完整的 CRUD 操作

BASE_URL="http://localhost:8080"
API_URL="$BASE_URL/api"

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 日志函数
log_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

log_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

log_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

# 检查服务器状态
check_server() {
    log_info "检查服务器状态..."
    if curl -f -s "$BASE_URL" > /dev/null; then
        log_success "服务器运行正常"
        return 0
    else
        log_error "服务器未启动或无法访问: $BASE_URL"
        return 1
    fi
}

# 用户登录获取 token
login() {
    log_info "用户登录..."
    
    # 发送验证码
    log_info "发送验证码到 13800138001..."
    SEND_CODE_RESPONSE=$(curl -s -X POST "$API_URL/auth/send-code" \
        -H "Content-Type: application/json" \
        -d '{
            "phone": "13800138001"
        }')
    
    echo "发送验证码响应: $SEND_CODE_RESPONSE"
    
    # 验证登录
    log_info "使用验证码登录..."
    LOGIN_RESPONSE=$(curl -s -X POST "$API_URL/auth/verify" \
        -H "Content-Type: application/json" \
        -d '{
            "phone": "13800138001",
            "verification_code": "123456"
        }')
    
    echo "登录响应: $LOGIN_RESPONSE"
    
    # 提取 token
    TOKEN=$(echo "$LOGIN_RESPONSE" | jq -r '.data.token // empty')
    
    if [ -n "$TOKEN" ] && [ "$TOKEN" != "null" ]; then
        log_success "登录成功，获取到 token"
        echo "Token: ${TOKEN:0:50}..."
        return 0
    else
        log_error "登录失败或无法获取 token"
        echo "完整响应: $LOGIN_RESPONSE"
        return 1
    fi
}

# 创建隧道映射
create_tunnel() {
    log_info "创建隧道映射..."
    
    CREATE_RESPONSE=$(curl -s -X POST "$API_URL/tunnels" \
        -H "Content-Type: application/json" \
        -H "Authorization: Bearer $TOKEN" \
        -d '{
            "service_name": "test-web-service",
            "local_ip": "127.0.0.1",
            "local_port": 3000,
            "tunnel_type": "http"
        }')
    
    echo "创建隧道响应: $CREATE_RESPONSE"
    
    # 检查是否成功
    SUCCESS=$(echo "$CREATE_RESPONSE" | jq -r '.success // false')
    if [ "$SUCCESS" = "true" ]; then
        TUNNEL_ID=$(echo "$CREATE_RESPONSE" | jq -r '.data.tunnel_id')
        log_success "隧道创建成功，ID: $TUNNEL_ID"
        echo "$TUNNEL_ID"
        return 0
    else
        log_error "隧道创建失败"
        return 1
    fi
}

# 获取隧道列表
list_tunnels() {
    log_info "获取隧道列表..."
    
    LIST_RESPONSE=$(curl -s -X GET "$API_URL/tunnels" \
        -H "Authorization: Bearer $TOKEN")
    
    echo "隧道列表响应: $LIST_RESPONSE"
    
    # 检查是否成功
    SUCCESS=$(echo "$LIST_RESPONSE" | jq -r '.success // false')
    if [ "$SUCCESS" = "true" ]; then
        COUNT=$(echo "$LIST_RESPONSE" | jq -r '.data.count // 0')
        log_success "获取隧道列表成功，共 $COUNT 个隧道"
        return 0
    else
        log_error "获取隧道列表失败"
        return 1
    fi
}

# 获取单个隧道详情
get_tunnel() {
    local tunnel_id="$1"
    log_info "获取隧道详情: $tunnel_id"
    
    GET_RESPONSE=$(curl -s -X GET "$API_URL/tunnels/$tunnel_id" \
        -H "Authorization: Bearer $TOKEN")
    
    echo "隧道详情响应: $GET_RESPONSE"
    
    # 检查是否成功
    SUCCESS=$(echo "$GET_RESPONSE" | jq -r '.success // false')
    if [ "$SUCCESS" = "true" ]; then
        SERVICE_NAME=$(echo "$GET_RESPONSE" | jq -r '.data.service_name')
        STATUS=$(echo "$GET_RESPONSE" | jq -r '.data.status')
        log_success "获取隧道详情成功，服务名: $SERVICE_NAME, 状态: $STATUS"
        return 0
    else
        log_error "获取隧道详情失败"
        return 1
    fi
}

# 更新隧道映射
update_tunnel() {
    local tunnel_id="$1"
    log_info "更新隧道映射: $tunnel_id"
    
    UPDATE_RESPONSE=$(curl -s -X PUT "$API_URL/tunnels/$tunnel_id" \
        -H "Content-Type: application/json" \
        -H "Authorization: Bearer $TOKEN" \
        -d '{
            "service_name": "updated-web-service",
            "local_ip": "127.0.0.1",
            "local_port": 3001,
            "tunnel_type": "http"
        }')
    
    echo "更新隧道响应: $UPDATE_RESPONSE"
    
    # 检查是否成功
    SUCCESS=$(echo "$UPDATE_RESPONSE" | jq -r '.success // false')
    if [ "$SUCCESS" = "true" ]; then
        NEW_PORT=$(echo "$UPDATE_RESPONSE" | jq -r '.data.local_port')
        log_success "隧道更新成功，新端口: $NEW_PORT"
        return 0
    else
        log_error "隧道更新失败"
        return 1
    fi
}

# 删除隧道映射
delete_tunnel() {
    local tunnel_id="$1"
    log_info "删除隧道映射: $tunnel_id"
    
    DELETE_RESPONSE=$(curl -s -X DELETE "$API_URL/tunnels/$tunnel_id" \
        -H "Authorization: Bearer $TOKEN")
    
    echo "删除隧道响应: $DELETE_RESPONSE"
    
    # 检查是否成功
    SUCCESS=$(echo "$DELETE_RESPONSE" | jq -r '.success // false')
    if [ "$SUCCESS" = "true" ]; then
        log_success "隧道删除成功"
        return 0
    else
        log_error "隧道删除失败"
        return 1
    fi
}

# 测试兼容性接口
test_legacy_api() {
    log_info "测试兼容性接口..."
    
    LEGACY_RESPONSE=$(curl -s -X POST "$API_URL/create/tunnel" \
        -H "Content-Type: application/json" \
        -H "Authorization: Bearer $TOKEN" \
        -d '{
            "localPort": "8080",
            "localHost": "127.0.0.1",
            "serverName": "legacy-test-service"
        }')
    
    echo "兼容性接口响应: $LEGACY_RESPONSE"
    
    # 检查是否成功
    SUCCESS=$(echo "$LEGACY_RESPONSE" | jq -r '.success // false')
    if [ "$SUCCESS" = "true" ]; then
        TUNNEL_ID=$(echo "$LEGACY_RESPONSE" | jq -r '.data.tunnelId')
        log_success "兼容性接口测试成功，隧道ID: $TUNNEL_ID"
        return 0
    else
        log_error "兼容性接口测试失败"
        return 1
    fi
}

# 主测试流程
main() {
    echo "======================================"
    echo "     隧道映射 API 测试开始"
    echo "======================================"
    
    # 检查依赖工具
    if ! command -v curl &> /dev/null; then
        log_error "curl 命令未找到，请先安装 curl"
        exit 1
    fi
    
    if ! command -v jq &> /dev/null; then
        log_error "jq 命令未找到，请先安装 jq"
        exit 1
    fi
    
    # 检查服务器
    if ! check_server; then
        exit 1
    fi
    
    # 用户登录
    if ! login; then
        exit 1
    fi
    
    echo ""
    echo "======================================"
    echo "     开始 CRUD 操作测试"
    echo "======================================"
    
    # 1. 创建隧道
    TUNNEL_ID=$(create_tunnel)
    if [ $? -ne 0 ]; then
        exit 1
    fi
    
    echo ""
    
    # 2. 获取隧道列表
    if ! list_tunnels; then
        exit 1
    fi
    
    echo ""
    
    # 3. 获取单个隧道详情
    if ! get_tunnel "$TUNNEL_ID"; then
        exit 1
    fi
    
    echo ""
    
    # 4. 更新隧道
    if ! update_tunnel "$TUNNEL_ID"; then
        exit 1
    fi
    
    echo ""
    
    # 5. 再次获取详情验证更新
    if ! get_tunnel "$TUNNEL_ID"; then
        exit 1
    fi
    
    echo ""
    
    # 6. 测试兼容性接口
    if ! test_legacy_api; then
        exit 1
    fi
    
    echo ""
    
    # 7. 删除隧道
    if ! delete_tunnel "$TUNNEL_ID"; then
        exit 1
    fi
    
    echo ""
    echo "======================================"
    echo "     所有测试完成！"
    echo "======================================"
    log_success "隧道映射 API 测试全部通过"
}

# 运行测试
main "$@"
